

var operators={
    //数组内全局变量 
    origin_data:[],//起始数据 用于数据筛选
    data:[],//数据（更新时同步的数据对象dataIdnex的来源）
    index:1,//页码
    dataIdnex:[],//当前页面展示的数据（更新时同步的数据对象）
    delet_no:[],//删除时操作的序号
    index_start:1,//展示页码的起始页码
    //configuration 传入参数配置插件
    options:{
        el:"",
        delet_status:"",
        modify_status:"",
        Length:"",
        sort_status:"",
        jstree:"",
    },
    // 初始化
    init:function(options){
        this.data=options.data; 
        this.origin_data=$.extend(true, [], options.data); 
        this.options.el=options.el;            
        this.options.modify_status=options.modify_status?true:false;        
        this.options.delet_status=options.delet_status?true:false; 
        this.options.sort_status=options.sort_status?true:false;
        this.options.jstree=options.jstree?true:false;
        if(this.options.jstree) {
          jstree.jsTreeShow("#modify_jstree");
          jstree.jsTreeChange("#modify_jstree","#modify_authorization");
          // jstree.jsTreeLoad("#modify_jstree",this.data[index].authorization);
        }
        this.options.Length=options.Length?options.Length:10; 
        this.options.delet_status?this.delet_check():null;
        this.options.sort_status?this._sort.init():null;
        this.update();
        this.box_check();
        this.updateIndex();
        this.bind_add();
        this.bind_update();
        // console.log(this.origin_data);
        // console.log(this.data);
    },
    // 更新（同步数据）
    update:function(){
        // this.dataIdnex;
        this.updateIndex();
        $(this.options.el).find("tbody").html("");
        for(let i=(this.index-1)*this.options.Length;i<=this.index*this.options.Length-1;i++){ 
            // console.log(this.data[i]);
            var dom=$(document.createElement("tr"));         
            if(this.data[i]){
                this.dataIdnex[i-(this.index-1)*this.options.Length]=this.data[i];
                dom.append('<td><input style="width:16px;" type="checkbox"></td><td>'+(i+1)+'</td>');
                for(let p in this.data[i]){
                  // console.log(data[i][p]);
                  if(p!="default"){dom.append('<td>'+this.data[i][p]+'</td>')};
                }
                doma=this.options.delet_status?'<a href="javascript:;" class="tpl-table-black-operation-del delete-op"  data-index='+i+'><i class="am-icon-trash"></i>删除</a>':'';
                domb=this.options.modify_status?'<a href="javascript:;" class="tpl-table-black-operation-mod set-pw"><i class="am-icon-pencil"></i>修改密码</a>':'';
                dom.append('<td><div class="tpl-table-black-operation">'+doma+domb+'</td>');
            }else{
                break;
            }  
            $(this.options.el).find("tbody").append(dom);

        }
        this.options.delet_status?this.bind_delet():false;
        this.options.modify_status?this.modify_pw():false;
    },
    // 页码组件更新
    updateIndex:function(){
        var paging=parseInt(this.data.length/this.options.Length);
        console.log(paging);
        var a=!(this.data.length%this.options.Length)?paging:paging+1;
        $(".am-pagination.tpl-pagination").html("");
        for(var i=0;i<=a-1;i++){
          var dom_li=document.createElement("li");
          var dom_a=document.createElement("a");
          dom_a.className="li_index";
          $(dom_a).text(i+1);
          $(dom_li).append(dom_a)
          $(".am-pagination.tpl-pagination").append(dom_li);
        }
        $(".am-pagination.tpl-pagination").find("a.li_index").on("click",function(){
          var index=$(this).text();
          operators.page(index);
        });
        $(".am-pagination.tpl-pagination").find("li.am-active").removeClass('am-active');
        this.index=!(this.data.length%this.options.Length)?this.index-1:this.index;
        $(".am-pagination.tpl-pagination").find("a.li_index").eq(this.index-1).parent("li").addClass('am-active');
        // console.log(paging);
        this.paging.init(paging);
    },
    // 翻页组件
    paging:{
      init:function(index){
        operators.data.length/operators.options.Length>=5?$(".paging_content").addClass('paging'):$(".paging_content").removeClass('paging');
        $(".paging").find(".content").find(".am-pagination.tpl-pagination").css("left",-(operators.index_start-1)*40+"px");
        this.bind_bt();
      },
      bind_bt:function(){
        var page_=parseInt(operators.data.length/operators.options.Length);
        $(".paging_content").find(".li_bt.bt_left").unbind().on("click",function(){
          operators.index>1?(operators.index-=1)?operators.index_start>=2&&operators.index<operators.index_start?(operators.index_start-=1):false:false:false; 
          operators.update();
        })
        $(".paging_content").find(".li_bt.bt_right").unbind().on("click",function(){
          operators.index<=page_?(operators.index=operators.index-0+1)?page_-operators.index_start>3&&operators.index>(operators.index_start+4)?(operators.index_start+=1):false:false:false; 
          operators.update();
        })
        $(".paging_content").find(".li_bt.bt_end").unbind().on("click",function(){
          operators.index!=page_+1?(operators.index=page_+1)&&(operators.index_start=page_-3):false; 
          operators.update();
        })
        $(".paging_content").find(".li_bt.bt_start").unbind().on("click",function(){
          operators.index!=1?(operators.index=1)&&(operators.index_start=1):false;
          operators.update();
        })
      },
    },
    // 翻页动作
    page:function(index){
        this.index=index;
        this.update();
    },
    // 删除动作
    delet:function(){
        for(i=0;i<=operators.delet_no.length-1;i++){
            this.data.splice(operators.delet_no[i]-i+(10*(operators.index-1)),1);
            this.origin_data.splice(operators.delet_no[i]-i+(10*(operators.index-1)),1);
        }              
        this.update();
        operators.delet_no=[];
        console.log(this.index);
        // console.log(this.dataIdnex);
    },
    // 增加动作
    add:function(options){
        this.data.push(options);
        this.update();
    },
    checke_add:function(options){

    },
    // 绑定删除
    bind_delet:function(){
      $('.widget-body.am-fr').find('.tpl-table-black-operation-del.delete-op').
        unbind().on('click', function() {
          var that=this;
          operators.delet_no=[];
          operators.delet_no.push($(that).closest('tr').index());
          // $('#delete-modal').modal({
          //   relatedTarget: this,
          //   onConfirm: function(options) {    
          //     operators.delet();
          //     $("#delete-modal").modal("close");
          //   },
          //   // closeOnConfirm: false,
          //   onCancel: function() {
          //     $("#delete-modal").modal("close");
          //   }
          // });
          layer.confirm('您是否删除本行？', {
            btn: ['删除','取消'] //按钮
          }, function(){
            operators.delet();
            layer.msg('删除成功', {icon: 1});
          }, function(){
            layer.msg('撤销删除', {icon: 2});
          });
        });

    },
    // 绑定修改密码
    modify_pw:function(){
        $('.widget-body.am-fr').find('.tpl-table-black-operation-mod.set-pw').
        on('click', function() {
          var that=this;
          $('#modify-pw-modal').modal({
            relatedTarget: this,
            onConfirm: function(e) {             
              layer.msg('您修改了密码', {time: 1000, icon:6});
              $('#modify-pw-modal').modal('close');
            },
            // closeOnConfirm: false,
            onCancel: function() {
              layer.msg('您取消了修改操作', {time: 1000, icon:6});
              $('#modify-pw-modal').modal('close');
            }
          });
        });
    },
    
    // 绑定添加
    bind_add:function(){
        $('#add-modal-toggle').on('click',function(){
            $('#add-modal').modal({
              relatedTarget: this,
              onConfirm: function(e) {
                // alert('你输入的是：' + e.data || '');
                // console.log()
                var status=true;
                for(var i in e.data){
                  status=e.data[i]?true:false;
                }
                if(status){
                    layer.msg('添加成功', {time: 1000, icon:6});
                    $('#add-modal').modal('close');
                    $('#add-modal').find("input").val("");
                }else{
                    layer.msg('您输入数据不完整', {time: 1000, icon:6});
                };                
              },
              onCancel: function(e) {
                layer.msg('您取消了添加操作', {time: 1000, icon:6});
                // operators.data.push();
                $('#add-modal').modal('close');
                $('#add-modal').find("input").val("");
              }
            });
        })
    },
    // 全选检测
    box_check:function(){
        $(operators.options.el).find("thead").find("[type=checkbox]:input")
        .unbind().on("click",function(){
            $(operators.options.el).find("tbody").find("[type=checkbox]:input").prop("checked",$(this).prop("checked"));
        })
    },
    // 多项删除工具
    delet_check:function(){
        $(operators.options.el).find("thead").find("[type=checkbox]:input")
        .unbind().on("click",function(){
            $(operators.options.el).find("tbody").find("[type=checkbox]:input").prop("checked",$(this).prop("checked"));
        })
        $("#delet_noes").unbind().on("click",function(){
            operators.delet_no=[];
            var $mm=$(operators.options.el).find("tbody").find("[type=checkbox]:input");
            $mm.each(function(index, el) {
                // console.log(el);
                if($(el).prop("checked")){
                   operators.delet_no.push($(el).closest('tr').index()); 
                }
            });
            // console.log(operators.delet_no);
          //   $('#delete-modal').modal({
          //   relatedTarget: this,
          //   onConfirm: function(options) {    
          //     operators.delet();
          //     $("#delete-modal").modal("close");
          //     $(operators.options.el).find("thead").find("[type=checkbox]:input").prop("checked",false)
          //   },
          //   // closeOnConfirm: false,
          //   onCancel: function() {
          //     $("#delete-modal").modal("close");
          //   }
          // });
          layer.confirm('您是否删除目标数据？', {
              btn: ['删除','取消'] //按钮
            }, function(){
              operators.delet();
              $(operators.options.el).find("thead").find("[type=checkbox]:input").prop("checked",false)
              layer.msg('删除成功', {icon: 1});
            }, function(){
              console.log(operators.options.el);
              $(operators.options.el).find("tbody").find("[type=checkbox]:input").prop("checked",false);
              layer.msg('撤销删除', {icon: 2});
            });
        })
    },
    // 更新工具绑定
    bind_update:function(){
        $("#bind_update").unbind().on("click",function(){
            operators.update();
            layer.msg("更新完成",{"icon":1})
        })
    },
    // 筛选组件
    _sort:{
        arry_key:["name","note","time","time"],
        init:function(){
           this.bind_sort("#sort_ex") ;
           operators.options._sort_arry_key?this.arry_key=operators.options._sort_arry_key:false;
        },
        sort_sum:function(key){
            var sum=[];
            for(var i in operators.data){
              // if(data[i][this.arry_key[0]]===key[0]){
              //   sum.push(data[i]);
              // }
              var status=[];
              status[0]=key[0]?operators.data[i][this.arry_key[0]]!=key[0]?false:true:true;
              status[1]=key[1]?operators.data[i][this.arry_key[1]]!=key[1]?false:true:true;
              status[2]=key[2]?!(operators.data[i][this.arry_key[2]].replace(/-/g,'')-0>=key[2]-0)?false:true:true;
              status[3]=key[3]?!(operators.data[i][this.arry_key[3]].replace(/-/g,'')-0<=key[3]-0)?false:true:true;
              // key[1]?key[2]?key[3]:
              // console.log(data[i][this.arry_key[2]].replace(/-/g,'')-0>=key[2]-0);
              // console.log(status[2]);
              // console.log(status[0]&&status[1]&&status[2]&&status[3]);
              status=status[0]&&status[1]&&status[2]&&status[3];
              status?sum.push(operators.data[i]):false;
            }
            console.log(sum);

            return sum;
        },
        // 绑定筛选
        bind_sort:function(id){
            $(id).find("button").on("click",function(){
                operators.data=$.extend(true, [],operators.origin_data); 
                var sum=[];
                var $node=$(id).find("input");
                sum=[$($node[0]).val(),$($node[1]).val(),$($node[2]).val().replace(/-/g,''),$($node[3]).val().replace(/-/g,'')]
                operators.data=operators._sort.sort_sum(sum);
                operators.index=1;
                operators.update();
                !operators.data.length?layer.msg("筛选方范围内无数据",{icon: 2}):layer.msg("筛选完成",{icon: 1});
            })
        }
    },
}

// js tree插件
var jstree={
  //显示jstree
    jsTreeShow:function(obj){
        var that = this;
        //清空实例
        $.jstree.destroy(obj);
        $(obj).jstree({
            "types":{
                "default":{
                    "icon":"glyphicon glyphicon-leaf"
                },
                "demo":{
                    "icon":"glyphicon glyphicon-ok"
                }
            },
            "plugins":["checkbox","types"],
            "core":{
                "data":treeData,
            }
        });
    },
    //监听jstree改变事件
    jsTreeChange:function(obj,target){
        $(obj).on("changed.jstree",function(e,data){
            $(target).val(data.selected);
        });
    },
    //jstree加载时改变select选项事件
    jsTreeLoad:function(obj,selectData){
        $(obj).on("loaded.jstree",function(e,data){
            var inst = data.instance;  
            if(selectData){
                for(var i = 0; i < selectData.length; i++){
                var item = selectData[i];
                inst.select_node(item);
              }
            }
        });
    }
}